#include "networkstatusdialog.h"
#include <QFont>
#include <QPixmap>
#include <QSpacerItem>
#include <QStyle>
#include <QGraphicsDropShadowEffect>
#include <QFrame>
#include <QGridLayout>
#include <QTimer>
#include <QIcon>
#include <QDebug>
#include <cstdio>
#include "networkdetaildialog.h"
#include <QLocale>
#include <QMainWindow>
#include "networkpropertydialog.h"
#include <QProcess> // Added for QProcess
#include <QRegularExpression> // Added for QRegularExpression

QGridLayout *m_bytesGrid = nullptr;
QWidget *m_centerWidget = nullptr;
QLabel *m_labelBytesTitle = nullptr;
QLabel *m_iconLabel = nullptr;
QLabel *m_labelTxBytesValue = nullptr;
QLabel *m_labelRxBytesValue = nullptr;
QString m_deviceName;
QTimer *m_statsTimer = nullptr;
NetworkInfo *m_networkInfo = nullptr;
QHBoxLayout *m_bytesRow = nullptr;
QSpacerItem *m_bytesSpacer = nullptr;
QSpacerItem *m_centerLeftSpacer = nullptr;

// 格式化字节数的静态函数
static QString formatBytes(qint64 bytes) {
    return QLocale::system().toString(bytes);
}

void NetworkStatusDialog::setStats(const NetworkStats &stats)
{
    // 更新字节数显示
    if (m_labelTxBytesValue) {
        m_labelTxBytesValue->setText(formatBytes(stats.bytesSent));
    }
    
    if (m_labelRxBytesValue) {
        m_labelRxBytesValue->setText(formatBytes(stats.bytesReceived));
    }
    
    // 如果没有找到对应的label，尝试通过对象名查找
    if (!m_labelTxBytesValue || !m_labelRxBytesValue) {
        QList<QLabel*> labels = this->findChildren<QLabel*>();
        for (QLabel* label : labels) {
            if (label->objectName().contains("tx", Qt::CaseInsensitive) && 
                label->objectName().contains("bytes", Qt::CaseInsensitive)) {
                label->setText(formatBytes(stats.bytesSent));
            } else if (label->objectName().contains("rx", Qt::CaseInsensitive) && 
                       label->objectName().contains("bytes", Qt::CaseInsensitive)) {
                label->setText(formatBytes(stats.bytesReceived));
            }
        }
    }
}

NetworkStatusDialog::NetworkStatusDialog(const ConnectionInfo &connInfo, const DeviceInfo &devInfo, NetworkInfo *networkInfo, QWidget *parent)
    : QDialog(parent), m_networkInfo(networkInfo)
{
    setWindowFlags((windowFlags() & ~Qt::WindowMaximizeButtonHint & ~Qt::WindowMinimizeButtonHint) | Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
    setWindowTitle(QString("%1 状态").arg(devInfo.name));
    setFixedSize(470, 600);
    setFixedSize(this->size());
    setStyleSheet("QDialog { background: #f5f6fa; }");
    QFont baseFont("微软雅黑", 10);
    this->setFont(baseFont);
    m_deviceName = devInfo.name;

    // ===== 主内容面板 =====
    QFrame *mainPanel = new QFrame(this);
    mainPanel->setStyleSheet("background: #fff; border-radius: 0; border: none;");
    QVBoxLayout *panelLayout = new QVBoxLayout(mainPanel);
    panelLayout->setContentsMargins(12, 24, 24, 24);
    panelLayout->setSpacing(0);

    // ===== 常规区 =====
    QLabel *labelGeneralTitle = new QLabel("常规", this);
    labelGeneralTitle->setFont(QFont(baseFont.family(), 11, QFont::Bold));
    labelGeneralTitle->setStyleSheet("color: #222;");
    panelLayout->addWidget(labelGeneralTitle);
    QFrame *lineGeneral = new QFrame(this);
    lineGeneral->setFrameShape(QFrame::HLine);
    lineGeneral->setStyleSheet("color: #e0e0e0; background: #e0e0e0; height:1px;");
    panelLayout->addWidget(lineGeneral);
    panelLayout->addSpacing(8);
    // 连接信息
    QGridLayout *infoGrid = new QGridLayout;
    infoGrid->setContentsMargins(0, 0, 0, 0);
    infoGrid->setHorizontalSpacing(18);
    infoGrid->setVerticalSpacing(12);
    QFont labelFont(baseFont.family(), 10);
    QFont valueFont(baseFont.family(), 10);
    valueFont.setBold(true);
    // 用真实数据填充
    QString ipv4;
    bool hasInternetV4 = false;
    if (!connInfo.ipAddress.isEmpty()) {
        // 同步检测Internet连通性
        QProcess pingProc;
        pingProc.start("ping", QStringList() << "-c" << "1" << "-W" << "1" << "8.8.8.8" << "-I" << connInfo.device);
        if (pingProc.waitForFinished(1500) && pingProc.exitCode() == 0) {
            hasInternetV4 = true;
        }
        ipv4 = hasInternetV4 ? "Internet" : "未连接";
    } else {
        ipv4 = "无网络访问权限";
    }
    QString ipv6;
    if (!connInfo.ipv6Address.isEmpty()) {
        ipv6 = connInfo.hasInternetV6 ? "Internet" : "未连接";
    } else {
        ipv6 = "无网络访问权限";
    }
    QString mediaStatus = devInfo.isEnabled ? "已启用" : "已禁用";
    QString duration = NetworkInfo::getConnectionDuration(connInfo);
    QString speed = !devInfo.speed.isEmpty() ? devInfo.speed : (!connInfo.speed.isEmpty() ? connInfo.speed : "-");

    // 统一去掉空格
    QString speedStr = speed;
    speedStr.replace(" ", "");

    // 匹配形如 "2000Mb/s"、"3000Mb/s"、"1000Mb/s"、"100Mb/s"
    QRegularExpression re("^(\\d+)Mb/s$", QRegularExpression::CaseInsensitiveOption);
    QRegularExpressionMatch match = re.match(speedStr);
    if (match.hasMatch()) {
        int mbps = match.captured(1).toInt();
        if (mbps >= 1000) {
            double gbps = mbps / 1000.0;
            speed = QString::number(gbps, 'f', 1) + " Gbps";
        } else {
            speed = QString::number(mbps) + " Mb/s";
        }
    }
    
    QStringList leftLabels = {"IPv4 连接:", "IPv6 连接:", "媒体状态:", "持续时间:", "速度:"};
    QStringList rightValues = { ipv4, ipv6, mediaStatus, duration, speed };
    for (int i = 0; i < leftLabels.size(); ++i) {
        QLabel *l = new QLabel(leftLabels[i], this);
        l->setFont(labelFont);
        l->setStyleSheet("color: #222;");
        l->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        infoGrid->addWidget(l, i, 0);
        QLabel *v = new QLabel(rightValues[i], this);
        v->setFont(valueFont);
        v->setStyleSheet("color: #222;");
        v->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        infoGrid->addWidget(v, i, 1);
    }
    panelLayout->addLayout(infoGrid);
    panelLayout->addSpacing(8);
    // 详细信息按钮
    QHBoxLayout *detailBtnLayout = new QHBoxLayout;
    QPushButton *btnDetail = new QPushButton("详细信息(E)...", this);
    btnDetail->setFixedSize(140, 32);
    btnDetail->setFont(QFont(baseFont.family(), 10));
    QString btnStyle = "QPushButton { background: #f5f6fa; border: 1px solid #d0d0d0; border-radius: 6px; } QPushButton:hover { background: #e6f0fa; }";
    btnDetail->setStyleSheet(btnStyle);
    detailBtnLayout->addWidget(btnDetail, 0, Qt::AlignLeft);
    detailBtnLayout->addStretch();
    panelLayout->addLayout(detailBtnLayout);
    panelLayout->addSpacing(18);

    // ===== 活动区 =====
    QLabel *labelActivityTitle = new QLabel("活动", this);
    labelActivityTitle->setFont(QFont(baseFont.family(), 11, QFont::Bold));
    labelActivityTitle->setStyleSheet("color: #222;");
    panelLayout->addWidget(labelActivityTitle);
    QFrame *lineActivity = new QFrame(this);
    lineActivity->setFrameShape(QFrame::HLine);
    lineActivity->setStyleSheet("color: #e0e0e0; background: #e0e0e0; height:1px;");
    panelLayout->addWidget(lineActivity);
    panelLayout->addSpacing(8);
    // 活动内容
    QHBoxLayout *iconRow = new QHBoxLayout;
    iconRow->addStretch();
    QLabel *labelTx = new QLabel("已发送", this);
    labelTx->setFont(labelFont);
    labelTx->setStyleSheet("color: #222;");
    iconRow->addWidget(labelTx);
    iconRow->addSpacing(8);
    QFrame *lineLeft = new QFrame(this);
    lineLeft->setFrameShape(QFrame::HLine);
    lineLeft->setFixedWidth(40);
    lineLeft->setFixedHeight(2);
    lineLeft->setStyleSheet("color: #b0b0b0; background: #b0b0b0;");
    iconRow->addWidget(lineLeft);
    iconRow->addSpacing(8);
    QLabel *iconLabel = new QLabel(this);
    iconLabel->setPixmap(QPixmap(":/icons/resources/net_connected.png").scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    iconLabel->setFixedSize(72, 72);
    iconLabel->setAlignment(Qt::AlignCenter);
    iconRow->addWidget(iconLabel);
    iconRow->addSpacing(8);
    QFrame *lineRight = new QFrame(this);
    lineRight->setFrameShape(QFrame::HLine);
    lineRight->setFixedWidth(40);
    lineRight->setFixedHeight(2);
    lineRight->setStyleSheet("color: #b0b0b0; background: #b0b0b0;");
    iconRow->addWidget(lineRight);
    iconRow->addSpacing(8);
    QLabel *labelRx = new QLabel("已接收", this);
    labelRx->setFont(labelFont);
    labelRx->setStyleSheet("color: #222;");
    iconRow->addWidget(labelRx);
    iconRow->addStretch();
    panelLayout->addLayout(iconRow);
    panelLayout->addSpacing(8);
    // 字节数行（动态spacing方案）
    QHBoxLayout *bytesRow = new QHBoxLayout;
    bytesRow->setContentsMargins(0, 0, 0, 0);
    bytesRow->setSpacing(0);
    QLabel *labelBytesTitle = new QLabel("字节:", this);
    labelBytesTitle->setFont(labelFont);
    labelBytesTitle->setStyleSheet("color: #222;");
    QFont bytesFont(baseFont.family(), 11, QFont::Bold);
    QLabel *labelTxBytes = new QLabel("0", this);
    labelTxBytes->setFont(bytesFont);
    labelTxBytes->setStyleSheet("color: #222;");
    QFrame *vLine = new QFrame(this);
    vLine->setFrameShape(QFrame::VLine);
    vLine->setFrameShadow(QFrame::Sunken);
    vLine->setFixedWidth(2);
    vLine->setFixedHeight(20);
    vLine->setStyleSheet("color: #b0b0b0; background: #b0b0b0;");
    QLabel *labelRxBytes = new QLabel("0", this);
    labelRxBytes->setFont(bytesFont);
    labelRxBytes->setStyleSheet("color: #222;");
    QWidget *centerWidget = new QWidget(this);
    QHBoxLayout *centerLayout = new QHBoxLayout(centerWidget);
    centerLayout->setContentsMargins(0, 0, 0, 0);
    centerLayout->setSpacing(16);
    QSpacerItem *centerLeftSpacer = new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Minimum);
    centerLayout->addItem(centerLeftSpacer);
    centerLayout->addWidget(labelTxBytes);
    centerLayout->addWidget(vLine);
    centerLayout->addWidget(labelRxBytes);
    centerLayout->setAlignment(Qt::AlignLeft);
    QSpacerItem *bytesSpacer = new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Minimum);
    bytesRow->addStretch();
    bytesRow->addWidget(labelBytesTitle, 0, Qt::AlignLeft);
    bytesRow->addItem(bytesSpacer);
    bytesRow->addWidget(centerWidget, 0, Qt::AlignVCenter);
    bytesRow->addStretch();
    panelLayout->addLayout(bytesRow);
    panelLayout->addSpacing(18);
    // 保存指针
    m_bytesRow = bytesRow;
    m_bytesSpacer = bytesSpacer;
    m_centerWidget = centerWidget;
    m_labelBytesTitle = labelBytesTitle;
    m_iconLabel = iconLabel;
    m_labelTxBytesValue = labelTxBytes;
    m_labelRxBytesValue = labelRxBytes;
    // 新增centerLeftSpacer指针
    m_centerLeftSpacer = centerLeftSpacer;
    // 首次显示时调整
    QTimer::singleShot(0, this, [this]{ adjustBytesGrid(); });

    // ===== 按钮区 =====
    QFont btnFont(baseFont.family(), 10);
    QPushButton *btnProperty = new QPushButton("属性(P)", this);
    btnProperty->setFixedSize(100, 36);
    btnProperty->setFont(btnFont);
    btnProperty->setIcon(QIcon(":/icons/resources/dp.png"));
    btnProperty->setStyleSheet(btnStyle);
    QPushButton *btnDisable = new QPushButton("禁用(D)", this);
    btnDisable->setFixedSize(100, 36);
    btnDisable->setFont(btnFont);
    btnDisable->setIcon(QIcon(":/icons/resources/dp.png"));
    btnDisable->setStyleSheet(btnStyle);
    QPushButton *btnDiagnose = new QPushButton("诊断(G)", this);
    btnDiagnose->setFixedSize(100, 36);
    btnDiagnose->setFont(btnFont);
    btnDiagnose->setIcon(style()->standardIcon(QStyle::SP_MessageBoxInformation));
    btnDiagnose->setStyleSheet(btnStyle);
    QPushButton *btnClose = new QPushButton("关闭(C)", this);
    btnClose->setFixedSize(100, 36);
    btnClose->setFont(btnFont);
    btnClose->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton));
    btnClose->setStyleSheet(btnStyle);
    // 第一行：操作按钮左对齐
    QHBoxLayout *opLayout = new QHBoxLayout;
    opLayout->setContentsMargins(12, 0, 0, 0);
    opLayout->setSpacing(18);
    opLayout->addWidget(btnProperty);
    opLayout->addWidget(btnDisable);
    opLayout->addWidget(btnDiagnose);
    opLayout->addStretch();
    // 第二行：关闭按钮右对齐
    QHBoxLayout *closeLayout = new QHBoxLayout;
    closeLayout->setContentsMargins(0, 0, 0, 0);
    closeLayout->addStretch();
    closeLayout->addWidget(btnClose);
    // 嵌套到一个竖直布局
    QVBoxLayout *btnsLayout = new QVBoxLayout;
    btnsLayout->setContentsMargins(0, 0, 0, 0);
    btnsLayout->setSpacing(8);
    btnsLayout->addLayout(opLayout);
    btnsLayout->addLayout(closeLayout);

    // ===== 总体布局 =====
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->addWidget(mainPanel);
    mainLayout->addSpacing(10);
    mainLayout->addLayout(btnsLayout);
    mainLayout->addSpacing(10);

    connect(btnClose, &QPushButton::clicked, this, &QDialog::accept);
    connect(btnDetail, &QPushButton::clicked, this, [=]{
        NetworkDetailDialog *dlg = new NetworkDetailDialog(connInfo, devInfo, this);
        dlg->exec();
        delete dlg;
    });
    connect(btnProperty, &QPushButton::clicked, this, [=]{
        NetworkPropertyDialog *dlg = new NetworkPropertyDialog(connInfo, devInfo, this);
        dlg->exec();
        delete dlg;
    });

    // 启动定时器，定时刷新字节数
    m_statsTimer = new QTimer(this);
    m_statsTimer->setInterval(500);
    bool ok = connect(m_statsTimer, &QTimer::timeout, this, [this]() {
        if (!m_deviceName.isEmpty()) {
            NetworkStats stats = NetworkInfo::getDeviceStatsFromProc(m_deviceName);
            setStats(stats);
        }
    });
    m_statsTimer->start();
    QTimer::singleShot(2000, this, [](){ });

    // 按钮功能连接
    connect(btnDisable, &QPushButton::clicked, this, [this]() {
        // 调用主窗口的禁用功能
        QWidget *p = this->parentWidget();
        while (p && !qobject_cast<QMainWindow*>(p)) p = p->parentWidget();
        if (auto mainWin = qobject_cast<QMainWindow*>(p)) {
            auto slot = mainWin->metaObject()->indexOfSlot("onDisableNetwork()");
            if (slot >= 0) QMetaObject::invokeMethod(mainWin, "onDisableNetwork");
        }
    });
    connect(btnDiagnose, &QPushButton::clicked, this, [this]() {
        // 调用主窗口的诊断功能
        QWidget *p = this->parentWidget();
        while (p && !qobject_cast<QMainWindow*>(p)) p = p->parentWidget();
        if (auto mainWin = qobject_cast<QMainWindow*>(p)) {
            auto slot = mainWin->metaObject()->indexOfSlot("onDiagnoseNetwork()");
            if (slot >= 0) QMetaObject::invokeMethod(mainWin, "onDiagnoseNetwork");
        }
    });
}

NetworkStatusDialog::~NetworkStatusDialog() {
    if (m_statsTimer) m_statsTimer->stop();
}

void NetworkStatusDialog::adjustBytesGrid() {
    if (!m_bytesRow || !m_bytesSpacer || !m_centerWidget || !m_iconLabel) return;
    // 获取iconLabel在mainPanel中的中心x坐标
    QPoint iconCenter = m_iconLabel->mapTo(this, QPoint(m_iconLabel->width()/2, m_iconLabel->height()/2));
    // 获取centerWidget中vLine在centerWidget内的中心x坐标
    QFrame *vLine = nullptr;
    QList<QFrame*> frames = m_centerWidget->findChildren<QFrame*>();
    for (QFrame *f : frames) {
        if (f->frameShape() == QFrame::VLine) { vLine = f; break; }
    }
    if (!vLine) return;
    QPoint vLineCenter = vLine->mapTo(this, QPoint(vLine->width()/2, vLine->height()/2));
    int dx = iconCenter.x() - vLineCenter.x();
    if (dx < 0) dx = 0;
    // 只调整centerWidget内部左侧spacer
    if (m_centerLeftSpacer) {
        static_cast<QSpacerItem*>(m_centerLeftSpacer)->changeSize(dx, 0, QSizePolicy::Fixed, QSizePolicy::Minimum);
        m_centerWidget->layout()->invalidate();
    }
}

void NetworkStatusDialog::resizeEvent(QResizeEvent *event) {
    QDialog::resizeEvent(event);
    adjustBytesGrid();
} 